#include "StdAfx.h"
#include "OSGViewMaker.h"
#include "ThreadPtr.h"

COSGViewer::COSGViewer(void)
{
	m_hCurrentWnd = NULL;
	m_thdCurrent = NULL;
}

COSGViewer::~COSGViewer(void)
{
	
}


void COSGViewer::Detach()
{
	m_glViewer.setDone(true);
	::WaitForSingleObject(this->m_thdCurrent->m_hThread, INFINITE);
	m_thdCurrent = NULL;
	m_hCurrentWnd = NULL;
	m_glViewer.setDone(false);
}

void COSGViewer::Attach(HWND hWnd)
{
	ASSERT(::IsWindow(hWnd));
	if(m_hCurrentWnd != hWnd)
	{
		this->Init(hWnd);
		m_hCurrentWnd = hWnd;
		m_glCamera->setGraphicsContext(m_glGC.get());
		m_glCamera->setViewport(m_glTraits->x, m_glTraits->y, m_glTraits->width, m_glTraits->height);
		if(NULL != m_thdCurrent)
		{
			//stop thread and make current null
			this->Detach();
		}
		m_glViewer.addSlave(m_glCamera.get());
		this->StartViewer();
	}
}

void COSGViewer::Init(HWND hWnd)
{
	RECT clientRect;
	m_glWinData = new osgViewer::GraphicsWindowWin32::WindowData(hWnd);
	m_glTraits = new osg::GraphicsContext::Traits;
	::GetClientRect(hWnd, &clientRect);

	/////init traits////////
	m_glTraits->inheritedWindowData = m_glWinData;
	m_glTraits->setInheritedWindowPixelFormat = true; 
	m_glTraits->windowDecoration = true; 
	m_glTraits->doubleBuffer = true; 
	m_glTraits->sharedContext = 0; 
	m_glTraits->supportsResize = true; 
	m_glTraits->x = 0; 
	m_glTraits->y = 0; 
	m_glTraits->width = clientRect.right - clientRect.left; 
	m_glTraits->height = clientRect.bottom - clientRect.top; 
	/////////

	//create graphics context using traits
	m_glGC = osg::GraphicsContext::createGraphicsContext(m_glTraits.get());

	//create camera
	m_glCamera = new osg::Camera;
}

void COSGViewer::StartViewer()
{
	m_thdCurrent = AfxBeginThread(StartViewerAdapter, this);
}

UINT COSGViewer::StartViewerAdapter(LPVOID viewer)
{
	if(NULL != viewer)
	{
		COSGViewer* pViewer = (COSGViewer*)viewer;
		pViewer->RunViewer();
	}
	return 0;
}

void COSGViewer::RunViewer()
{
	m_glViewer.run();
}

void COSGViewer::SetSceneData(osg::ref_ptr<osg::Group> root)
{
	//CThreadPtr<osgViewer::Viewer> spViewer(&m_glViewer);
	m_glViewer.setSceneData(root.get());
}





